package cn1shared.net;

import java.io.InputStream;
import java.io.IOException;


public final class LimitedInputStream extends InputStream {
	private final InputStream in;
	private long left;

	public LimitedInputStream(InputStream in,long length) {
		this.in = in;
		this.left = length;
	}

	private void dec(long n) {
		left -= n;
		if( left < 0 )
			throw new RuntimeException();
//System.out.println("left "+left);
	}

	public int read() throws IOException {
		if( left == 0 )
			return -1;
		dec(1);
		return in.read();
	}

	public int read(byte[] b,int off,int len) throws IOException {
		if( left == 0 )
			return -1;
		if( len > left )
			len = (int)left;
		int rtn = in.read(b,off,len);
		if( rtn > 0 )
			dec(rtn);
		return rtn;
	}

	public long skip(long n) throws IOException {
		if( n > left )
			n = left;
		long rtn = in.skip(n);
		dec(rtn);
		return rtn;
	}

	public int available() throws IOException {
		int rtn = super.available();
		if( rtn > left )
			rtn = (int)left;
		return rtn;
	}

	public void close() throws IOException {
		// leave it open
	}

}
